package com.ruoyi.system.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.service.impl.TestServiceImpl;
import org.apache.commons.collections4.Get;
import org.apache.tomcat.jni.Directory;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Test;
import com.ruoyi.system.service.ITestService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2021-07-07
 */
@RestController
@RequestMapping("/system/test")
@Scope("prototype")
public class AaTestController extends BaseController
{
    @Autowired
    private ITestService testService;
    
    private static int st = 0;      //静态的
    private int index = 0;    //非静态
    
    /**
     * 保存文件到mysql
     */
    @GetMapping("/testSpringBeab")
    public int testSpringBeab(){
        //System.out.println(st++ + " | " + index++);
        System.out.println("testRest");
        System.out.println("1");
        System.out.println("4");
        System.out.println("5");
        return testService.testSpringBeab();
    }
    
    /**
     * 保存文件到mysql
     */
    @PostMapping("/insertFile")
    public String insertFile(MultipartFile multipartFile){
        try{
            byte[] bytes = multipartFile.getBytes();
            if(bytes.length > 4*1024*1024){
                return "上传失败，文件大小超出4M";
            }
    
            BASE64Encoder bEncoder = new BASE64Encoder();
            String[] suffixArra = multipartFile.getOriginalFilename().split("\\.");
    
            String encode = bEncoder.encode(bytes);
    
            String preffix="data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);
            String base64EncoderImg = preffix + bEncoder.encode(bytes).replaceAll("[\\s*\t\n\r]", "");
            
            
    
            Test test = new Test();
            test.setAa("aa");
            test.setUpdateDate(new Date());
            test.setImage(encode);
            this.testService.insertTest(test);
    
        }catch(IOException e){
            e.printStackTrace();
        }
        return "success";
    }
    
    /**
     * 保存文件到mysql
     */
    @PostMapping("/getFile")
    public String getFile(HttpServletResponse response){
        response.setContentType("image/png;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName=ss");
        
        Test test = testService.selectTestById(12L);
        String base64Code = test.getImage();
    
        convertBase64ToImage(base64Code);
    
        return "success";
    }
    
    /**
     * base转图片
     */
    private static void convertBase64ToImage(String base64Code){
        BufferedImage image = null;
        
        byte[] imageByte = null;
        
        try {
            imageByte = DatatypeConverter.parseBase64Binary(base64Code);
            
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(byteArrayInputStream);
            
            bis.close();
            
            File outputfile = new File("D:\\06data\\text1.png");
            
            ImageIO.write(image, "png", outputfile);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:test:list')")
    @GetMapping("/list")
    public TableDataInfo list(Test test)
    {
        startPage();
        List<Test> list = testService.selectTestList(test);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:test:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Test test)
    {
        List<Test> list = testService.selectTestList(test);
        ExcelUtil<Test> util = new ExcelUtil<Test>(Test.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:test:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(testService.selectTestById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:test:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Test test)
    {
        return toAjax(testService.insertTest(test));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:test:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Test test)
    {
        return toAjax(testService.updateTest(test));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:test:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(testService.deleteTestByIds(ids));
    }
}
